package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Travel;
import cn.wolfcode.wolf2w.exception.LoginException;
import cn.wolfcode.wolf2w.query.TravelQuery;
import cn.wolfcode.wolf2w.repository.TravelRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.PageHelperUtil;
import cn.wolfcode.wolf2w.vo.TravelVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.swing.plaf.nimbus.State;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * Created by 甘静斌 on 2020-08-07 13:41
 */
@Service
//@Transactional
public class TravelServiceImpl implements ITravelService {

    @Autowired
    private TravelRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private ITravelService travelService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Travel travel) {
        //如果id为 "" ,spring-data-mongodb 不会自动生成id注入
        travel.setId(null);
        repository.save(travel);
    }

    @Override
    public void update(Travel travel) {

        repository.save(travel);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public Travel get(String id) {

        Optional<Travel> op = repository.findById(id);
        if (op.isPresent()){
            Travel travel = op.get();
            travel.setAuthor(userInfoService.get(travel.getUserId()));

            return  travel;
        }

        return null;
    }

    @Override
    public List<Travel> list() {


        return repository.findAll();
    }

    @Override
    public Page<Travel> query(TravelQuery qo) {

        //查询封装类
        Query query = new Query();
        //分页数据 , currentPage , pageSite

        //游记管理关键字查询
        if (qo.getState() == Travel.STATE_WAITING || qo.getState() == Travel.STATE_REJECT){
            Criteria criteria = Criteria.where("state").is(qo.getState());
            query.addCriteria(criteria);
        }
        //Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize() ,Sort.Direction.ASC,"_id");

        //游记关于出行天数排序
        if (qo.getDayType() > Travel.DAYTYPE){
            TravelVO vo = TravelVO.getDay(qo.getDayType());
            Criteria criteria = Criteria.where("day").gte(vo.getMin()).lte(vo.getMax());
            query.addCriteria(criteria);
        }
        //指定目的地排序
        if (StringUtils.hasLength(qo.getDestId())){
            Criteria criteria = Criteria.where("destId").is(qo.getDestId());
            query.addCriteria(criteria);
        }
        //游记人均消费排序
        if (qo.getPerExpendType() > Travel.PEREXPENDTYPE){
            TravelVO expendType = TravelVO.getperExpendType(qo.getPerExpendType());
            Criteria criteria = Criteria.where("perExpend").gte(expendType.getMin()).lte(expendType.getMax());
            query.addCriteria(criteria);

        }

        //最新游记和最热游记
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");
        if (qo.getOrderType() == Travel.ORDERTYPENEW){

            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "viewnum");
        }else if(qo.getOrderType() == Travel.ORDERTYPEHOT){
            pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "lastUpdate");
        }

        //后台游记管理,查询出author作者的数据
        Page<Travel> page = PageHelperUtil.query(template, pageable, Travel.class, query, qo);
        for (Travel travel : page) {
            travel.setAuthor(userInfoService.get(travel.getUserId()));
        }

        //list Pageable total 封装三个数据,返回给页面
        return page;
    }

    @Override
    public Travel saveOrUpdate(Travel travel) {

        //目的地名称
        Destination destination = destinationService.get(travel.getDestId());
        travel.setDestName(destination.getName());

        travel.setReleaseTime(null);
        //用户id   通过token去拿

        //发布时间
        travel.setCreateTime(new Date());

        //最后更新时间
        travel.setLastUpdateTime(new Date());
        if (StringUtils.hasLength(travel.getId())){

            Travel tr = this.get(travel.getId());
            travel.setFavornum(tr.getFavornum());
            travel.setReplynum(tr.getReplynum());
            travel.setSharenum(tr.getSharenum());
            travel.setThumbsupnum(tr.getThumbsupnum());
            travel.setViewnum(tr.getViewnum());
            this.update(travel);
        }else {
            this.save(travel);
        }
        return travel;
    }

    /**
     * 后端改变审核状态
     * @param id
     * @param state
     */
    @Override
    public void changeState(String id, int state) {

        //根据查询id,获取travel对象
        Travel travel = travelService.get(id);
        if (travel == null || travel.getState() != Travel.STATE_WAITING){
            throw new LoginException("参数异常!");
        }

        //当游记通过审核后
        if (Travel.STATE_RELEASE == state){
            //游记状态改为审核通过
            travel.setState(Travel.STATE_RELEASE);
            //发布时间改为当前时间
            travel.setCreateTime(new Date());
            //最后更新时间改为当前时间
            travel.setLastUpdateTime(new Date());
        }else if(Travel.STATE_REJECT== state){
            //当审核被拒绝后
            //状态改为拒绝
            travel.setState(Travel.STATE_REJECT);
            //发布时间改为null
            travel.setCreateTime(null);
            //最后更新时间改为当前时间
            travel.setLastUpdateTime(new Date());
        }

        this.update(travel);

    }

    @Override
    public void updateState(String id, int state) {

        Query query = new Query();

        query.addCriteria(Criteria.where("id").is(id));
        Update update = new Update();
        update.set("state",state );

        template.updateMulti(query,update ,Travel.class );

    }

    /**
     * 点击量前三的游记文章
     * @param destId
     * @return
     */
    @Override
    public List<Travel> queryByDestId(String destId) {


        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.ASC, "viewnum");
        List<Travel> list = repository.findByDestId(destId,pageable);

        return list;
    }


}
